<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="指标名称">
        <px-input v-model="queryParams.name" placeholder="请输入" clearable />
      </px-form-item>
      <px-form-item label="所属厂区">
        <px-select v-model="queryParams.level" :disabled="facDisabled" placeholder="请选择" clearable style="width: 240px" filterable>
          <px-option v-for="dict in levList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item label="结果状态">
        <px-select v-model="queryParams.resultStatus" placeholder="请选择" clearable style="width: 240px" filterable>
          <px-option v-for="dict in statusList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item label="监控周期">
        <px-select v-model="queryParams.cycle" placeholder="请选择" clearable style="width: 240px" filterable>
          <px-option v-for="dict in cycleList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemName" />
        </px-select>
      </px-form-item>
      <px-form-item style="width: 280px !important" label="监控范围">
        <px-date-picker
          v-model="dateRange"
          type="daterange"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>

    <px-table v-if="!addVisible && !detailVisible" v-loading="loading" :data="typeList" height="calc(100vh - 269px)" border>
      <px-table-column label="序号" fixed="left" type="index" width="70">
        <template #default="{ $index }">
          {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </px-table-column>
      <px-table-column label="指标名称" fixed width="210" prop="name">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </px-table-column>

      <px-table-column label="所属厂区" fixed width="180" prop="category">
        <template #default="scope">
          <span>{{ scope.row.level }}</span>
        </template>
      </px-table-column>

      <px-table-column label="监控周期" prop="cycle">
        <template #default="scope">
          <span>{{ scope.row.cycle }}</span>
        </template>
      </px-table-column>

      <px-table-column label="监控范围" width="120" prop="calculateTime">
        <template #default="scope">
          <span>{{ translateTime(scope.row.cycle, scope.row.calculatePeriod) }}</span>
        </template>
      </px-table-column>
      <px-table-column label="限值方式" prop="limitMethod">
        <template #default="scope">
          <span>{{ scope.row.limitMethod }}</span>
        </template>
      </px-table-column>
      <px-table-column width="140" label="环比/正常范围">
        <template #default="scope">
          <span v-if="scope.row.limitMethod == '百分比'">{{ scope.row.mom }}% /{{ scope.row.normalRange }}%</span>
          <span v-else> {{ scope.row.mom }}/- </span>
        </template>
      </px-table-column>
      <px-table-column width="140" label="计算结果 (tCO₂e)" prop="result">
        <template #default="scope">
          <span>{{ scope.row.result }}</span>
        </template>
      </px-table-column>
      <px-table-column width="140" label="正常范围(tCO₂e)" prop="limitMethod">
        <template #default="scope">
          <span>{{ scope.row.normalRangeMin }}~{{ scope.row.normalRangeMax }}</span>
        </template>
      </px-table-column>
      <px-table-column label="结果状态" width="100" prop="relatedEnergy">
        <template #default="scope">
          <span v-if="scope.row.resultStatus == 'N'" class="status-value"><span class="status-icon" />正常</span>
          <span v-else-if="scope.row.resultStatus == 'W'" class="status-value2"><span class="status-icon2" />告警</span>
          <span v-else>无</span>
        </template>
      </px-table-column>
      <px-table-column label="异常原因" prop="createByName">
        <template #default="scope">
          <span v-if="scope.row.alarmId != null" style="color: #4e8ef6; cursor: pointer" @click="viewalarmId(scope.row.alarmId)">查看</span>
          <span v-else>-</span>
        </template>
      </px-table-column>
      <px-table-column label="指标创建人" width="100" prop="createByName">
        <template #default="scope">
          <span>{{ scope.row.createByName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="计算时间" width="160" prop="calculateTime">
        <template #default="scope">
          <span>{{ scope.row.calculateTime }}</span>
        </template>
      </px-table-column>
      <px-table-column label="计算人" width="160" prop="updateByName">
        <template #default="scope">
          <span v-if="scope.row.calculateByName == null">自动计算</span>
          <span v-else>{{ scope.row.calculateByName }}</span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="180">
        <template #default="scope">
          <px-button v-has="'ALL_DOUBLE_CARBON_CARBONINDEX_INDEXCALCULATIONLEDGER_PROTOTYPE'" link type="primary" @click="handlehalarm(scope.row)">
            <px-tooltip class="box-item" content="选择异常原因" placement="top">
              <px-icon :size="20"><AddRectangle /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'ALL_DOUBLE_CARBON_CARBONINDEX_INDEXCALCULATIONLEDGER_DETAIL'" link type="primary" @click="handlehistory(scope.row.id)">
            <px-tooltip class="box-item" content="历史记录" placement="top">
              <p><indexhistory /></p> </px-tooltip
          ></px-button>
          <px-button
            v-if="scope.row.status != 'INVALID'"
            v-has="'ALL_DOUBLE_CARBON_CARBONINDEX_INDEXCALCULATIONLEDGER_EDITOR'"
            link
            type="primary"
            @click="handleCom(scope.row.id)"
          >
            <px-tooltip class="box-item" content="重算" placement="top">
              <p><indexcom /></p> </px-tooltip
          ></px-button>
          <px-button
            v-if="scope.row.status != 'INVALID'"
            v-has="'ALL_DOUBLE_CARBON_CARBONINDEX_INDEXCALCULATIONLEDGER_DELETE'"
            link
            type="danger"
            @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon><Delete /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <px-dialog v-model="innerVisible" width="917" title="历史记录" align-center>
      <px-table v-loading="loading" :data="rukuList" height="calc(100vh - 339px)" show-overflow-tooltip highlight-current-row border>
        <!-- <px-table-column type="selection" width="40" /> -->
        <px-table-column label="计算结果（tCO₂e）" prop="inboundNumber">
          <template #default="scope">
            <span>{{ scope.row.result }}</span>
          </template>
        </px-table-column>
        <px-table-column width="140" label="环比/正常范围">
          <template #default="scope">
            <span v-if="scope.row.limitMethod == '百分比'">{{ scope.row.mom }}% /{{ scope.row.normalRange }}%</span>
            <span v-else> {{ scope.row.mom }}/- </span>
          </template>
        </px-table-column>
        <px-table-column width="140" label="正常范围" prop="limitMethod">
          <template #default="scope">
            <span>{{ scope.row.normalRangeMin }}~{{ scope.row.normalRangeMax }}</span>
          </template>
        </px-table-column>
        <px-table-column label="结果状态" prop="gasType">
          <template #default="scope">
            <span v-if="scope.row.resultStatus == 'N'" class="status-value"><span class="status-icon" />正常</span>
            <span v-else-if="scope.row.resultStatus == 'W'" class="status-value2"><span class="status-icon2" />告警</span>
            <span v-else>无</span>
          </template>
        </px-table-column>
        <px-table-column label="计算时间" prop="releaseYear">
          <template #default="scope">
            <span>{{ scope.row.calculateTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="计算人" prop="value">
          <template #default="scope">
            <span v-if="scope.row.calculateByName == null">自动计算</span>
            <span v-else>{{ scope.row.calculateByName }}</span>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>

      <pagination
        v-show="total2 > 0"
        v-model:page="queryParams2.pageNum"
        v-model:limit="queryParams2.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="getRukuList"
      />
    </px-dialog>
    <px-dialog v-model="alarmVisible" width="1255" title="异常原因" align-center>
      <px-table v-loading="loading" :data="alarmList" height="calc(100vh - 339px)" show-overflow-tooltip highlight-current-row border>
        <!-- <px-table-column type="selection" width="40" /> -->
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="monitorTypeName" label="监控类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="spcConfigName" label="报警项" min-width="100" show-overflow-tooltip />
        <!-- <px-table-column prop="energyTypeName" label="能源类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="energyName" label="能源" min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="period" label="监控周期" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ formatPeriod(scope.row.period) }}
          </template>
        </px-table-column>
        <px-table-column prop="alarmTime" label="报警时间" min-width="100" show-overflow-tooltip />
        <px-table-column prop="alarmLevel" label="报警等级" min-width="120" show-overflow-tooltip align="center">
          <template #default="scope">
            <span v-if="scope.row.alarmLevel === null">""</span>
            <px-tag v-else :type="scope.row.alarmLevel === 'S' ? 'warning' : 'danger'">{{ formatAlarm(scope.row.alarmLevel) }}</px-tag>
          </template>
        </px-table-column>
        <px-table-column prop="alarmValue" label="报警值" min-width="120" show-overflow-tooltip />
        <px-table-column prop="spcThreshold" label="厂务内控值" min-width="100" show-overflow-tooltip />
        <px-table-column prop="hseThreshold" label="HSE管控值" min-width="100" show-overflow-tooltip />
        <px-table-column prop="eventType" label="状态" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            <div class="flex-center" :style="{ color: eventTypeStyle(scope.row.eventType) }">
              <span class="point mg-r-8" :style="{ background: eventTypeStyle(scope.row.eventType) }" />
              <span>{{ formatEventType(scope.row.eventType) }}</span>
            </div>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-button link type="primary" @click="viewalarmId(scope.row.id)">
              <px-tooltip class="box-item" content="查看" placement="top">
                <px-icon :size="20"><Tickets /></px-icon></px-tooltip
            ></px-button>
            <px-button link type="primary" @click="handleaddalarm(scope.row.id)">
              <px-tooltip class="box-item" content="关联" placement="top">
                <px-icon :size="20"><AddRectangle /></px-icon> </px-tooltip
            ></px-button>
          </template>
        </px-table-column>

        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>

      <pagination
        v-show="total3 > 0"
        v-model:page="queryParams3.pageNum"
        v-model:limit="queryParams3.pageSize"
        style="margin-bottom: -10px"
        :total="total3"
        @pagination="getalarmList"
      />
    </px-dialog>
    <div v-if="addVisible" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button type="primary" @click="equipopenDetailsubmitForm(detailruleFormRef)">保存</px-button>
    </div>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue, dictItemqueryListByTypeCode } from "@/api/waterClass";
import { queryListPagepull, queryDetailpull, addpull, updatepull, deletepull, queryListPageForOutbound } from "@/api/hazardousWasteS";
import { facilityquery, facilitysave, facilitydelete, facilitydetail, facilityedit } from "@/api/doubleCarbonManage/accountingList";
import { emissionFactorquery } from "@/api/doubleCarbonManage/carbonAccounting";
import indexhistory from "@/assets/svg/indexhistory.svg?component";
import indexcom from "@/assets/svg/indexcom.svg?component";
import { formatPeriod, formatAlarm, formatEventType, eventTypeStyle } from "./utils";
const router = useRouter();
import {
  emissionIndicatorLedgerlistLedgel,
  emissionIndicatorLedgercalculate,
  emissionIndicatorLedgerdeleteLedge,
  emissionIndicatorLedgerlistHistory,
  consumptionMonitorlistAlarm,
  emissionIndicatorLedgerlinkAlarm
} from "@/api/doubleCarbonManage/indexManage";
const jibenxinxiFlg = ref(true);
const jiqicanshuFlg = ref(true);
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const detailruleFormRef = ref();
const addchukuList = () => {
  progressVisible.value = true;
  queryParams2.value.dictWasteCode = "";
  getRukuList();
};
const handleaddalarm = id => {
  console.log(id);
  emissionIndicatorLedgerlinkAlarm({
    indicatorLedgeId: indicatorLedgeId.value,
    alarmId: id
  }).then(res => {
    alarmVisible.value = false;
    PxMessage({
      message: "管理成功",
      type: "success"
    });
    getList();
  });
};
let facDisabled = ref(false);
onMounted(() => {
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      facDisabled.value = true;
      queryParams.value.level = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      facDisabled.value = false;
      queryParams.value.level = null;
      getList();
    }
  }
});
const { proxy }: any = getCurrentInstance();
function equipopenDetailcancel() {
  console.log(buttonTitle.value);
  if (buttonTitle.value == "新增") {
    if (
      equipdata.value.name != "" ||
      equipdata.value.serialNumber != "" ||
      equipdata.value.category != "" ||
      equipdata.value.relatedEnergy != "" ||
      equipdata.value.emissionFactorId != "" ||
      equipdata.value.emissionFactorName != "" ||
      equipdata.value.unit != "" ||
      equipdata.value.factorSource != "" ||
      equipdata.value.activityLevelUnit != "" ||
      equipdata.value.unitConversionRatio != null ||
      equipdata.value.emissionCategory != "" ||
      equipdata.value.releaseYear != null ||
      equipdata.value.value != null ||
      equipdata.value.standardValueList.length > 0
    ) {
      PxMessageBox.confirm("<p>取消将不保存当前录入信息返回上一页</p><p>确定取消吗？</p>", "温馨提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          addVisible.value = false;
        })
        .catch(() => {});
    } else {
      addVisible.value = false;
    }
  } else {
    addVisible.value = false;
  }
}

const typeList = ref([]);
const progressVisible = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const addVisible = ref(false);
const detailVisible = ref(false);
const innerVisible = ref(false);
const total = ref(0);
const total2 = ref(0);
const total3 = ref(0);
const dateRange = ref([]);
const alarmVisible = ref(false);
// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const indicatorLedgeId = ref("");
const data = reactive({
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: {},
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  wasteUnitoptions: [
    {
      value: "克",
      label: "克"
    },
    {
      value: "千克",
      label: "千克"
    },
    {
      value: "吨",
      label: "吨"
    }
  ],
  photoStatusFlag: false,
  fileStatusFlag: false,
  equipdata: {
    id: "",
    name: "",
    serialNumber: "",
    category: "",
    relatedEnergy: "",
    emissionFactorId: "",
    emissionFactorName: "",
    unit: "",
    factorSource: "",
    activityLevelUnit: "",
    unitConversionRatio: null,
    emissionCategory: "",
    standardValueList: [],
    createByName: "",
    updateByName: "",
    releaseYear: "",
    value: ""
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "",
    isAsc: "",
    name: "",
    level: "",
    cycle: "",
    resultStatus: "",
    calculateTimeStart: "",
    calculateTimeEnd: "",
    orderBy: ""
  },
  queryParams2: {
    orderByColumn: "",
    isAsc: "",
    id: 0,
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  queryParams3: {
    pageNum: 1,
    pageSize: 20,
    alarmLevel: "",
    kind: "C",
    period: null,
    alarmTimeStart: "",
    alarmTimeEnd: "",
    energyType: null,
    monitorType: ""
  },
  rules: {
    name: [{ required: true, message: "不能为空", trigger: "blur" }],
    serialNumber: [{ required: true, message: "不能为空", trigger: "blur" }],
    category: [{ required: true, message: "不能为空", trigger: "change" }],
    activityLevelUnit: [{ required: true, message: "不能为空", trigger: "change" }],
    emissionFactorName: [{ required: true, message: "不能为空", trigger: "blur" }],
    value: [{ required: true, message: "不能为空", trigger: "blur" }],
    factorSource: [{ required: true, message: "不能为空", trigger: "blur" }],
    releaseYear: [{ required: true, message: "不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "不能为空", trigger: "blur" }],
    unitConversionRatio: [{ required: true, message: "不能为空", trigger: "blur" }],
    emissionCategory: [{ required: true, message: "不能为空", trigger: "change" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  levelUnitList: [],
  energyList: [],
  categoryTypeList: [],
  SourceList: [],
  selectrow: null,
  levList: [
    { itemName: "全厂", itemValue: null },
    { itemName: "创新中心一期", itemValue: "创新中心一期" },
    { itemName: "创新中心二期", itemValue: "创新中心二期" }
  ],
  cycleList: [
    {
      itemName: "年"
    },
    {
      itemName: "月"
    },
    {
      itemName: "日"
    }
  ],
  statusList: [
    {
      itemName: "正常",
      itemValue: "N"
    },
    {
      itemName: "告警",
      itemValue: "W"
    }
  ],
  alarmList: []
});
const selectyinzi = () => {
  getRukuList();
  innerVisible.value = true;
};

const {
  queryParams3,
  alarmList,
  levList,
  cycleList,
  statusList,
  liquidList,
  selectRukuList,
  queryParams,
  SourceList,
  levelUnitList,
  energyList,
  categoryTypeList,
  queryParams2,
  form,
  rules,
  equipdata,
  rukuList,
  selectrow
} = toRefs(data);
const getqueryCategoryList = () => {
  queryChildByTypeCodeAndItemValue({
    value: "EMISSION_FACTOR_SOURCE",
    typeCode: "BICARBON"
  }).then((response: any) => {
    SourceList.value = response;
  });
  //设施活动类别
  queryChildByTypeCodeAndItemValue({
    value: "FACILITY_CATEGORY",
    typeCode: "BICARBON"
  }).then((response: any) => {
    //console.log(response);
    liquidList.value = response;
  });
  //活动水平单位
  queryChildByTypeCodeAndItemValue({
    value: "ACTIVITY_LEVEL_UNIT",
    typeCode: "BICARBON"
  }).then((response: any) => {
    //console.log(response);
    levelUnitList.value = response;
  });
  //关联能源数据
  queryChildByTypeCodeAndItemValue({
    value: "RELATED_ENERGY",
    typeCode: "BICARBON"
  }).then((response: any) => {
    //console.log(response);
    energyList.value = response;
  });
  //排放类别
  queryChildByTypeCodeAndItemValue({
    value: "EMISSION_CATEGORY",
    typeCode: "BICARBON"
  }).then((response: any) => {
    //console.log(response);
    categoryTypeList.value = response;
  });
};
const handledelAddPosition = () => {
  equipdata.value.standardValueList.push({
    level: "",
    targetValue: null,
    benchmarkValue: null,
    complianceValue: null
  });
};
const handelRadio = row => {
  selectrow.value = row;
};
function handleDeleteceng(row) {
  PxMessageBox.confirm('是否确认删除"' + row.content + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  });
  emissionIndicatorLedgerdeleteLedge({ id: row.id })
    .then(async () => {
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}
const addsave = () => {};
getqueryCategoryList();
function getRukuList() {
  loading.value = true;

  emissionIndicatorLedgerlistHistory(queryParams2.value).then((response: any) => {
    rukuList.value = response.data;
    total2.value = response.total;
    loading.value = false;
  });
}
const getlastday = date => {
  date.setMonth(date.getMonth() + 1, 1);
  date.setDate(date.getDate() - 1);
  return date.getDate();
};
function getalarmList(row) {
  loading.value = true;
  if (row.cycle == "日") {
    queryParams3.value.alarmTimeStart = `${row.calculatePeriod.slice(0, 10)} 00:00:00`;
    queryParams3.value.alarmTimeEnd = `${row.calculatePeriod.slice(0, 10)} 23:59:59`;
  }
  if (row.cycle == "月") {
    var today = new Date(row.calculatePeriod);
    queryParams3.value.alarmTimeStart = `${row.calculatePeriod.slice(0, 7)}-01 00:00:00`;
    queryParams3.value.alarmTimeEnd = `${row.calculatePeriod.slice(0, 7)}-${getlastday(today)} 23:59:59`;
  }
  if (row.cycle == "年") {
    queryParams3.value.alarmTimeStart = `${row.calculatePeriod.slice(0, 4)}-01-01 00:00:00`;
    queryParams3.value.alarmTimeEnd = `${row.calculatePeriod.slice(0, 4)}-12-31 23:59:59`;
  }

  consumptionMonitorlistAlarm(queryParams3.value).then((response: any) => {
    alarmList.value = response.data;
    total3.value = response.total;
    loading.value = false;
  });
}
const viewalarmId = id => {
  console.log(id);
  router.push({ path: "/common/energy/monitor/monitorEvent", query: { id: id } });
};
function getList() {
  loading.value = true;
  if (dateRange.value != null) {
    queryParams.value.calculateTimeStart = dateRange.value[0];
    queryParams.value.calculateTimeEnd = dateRange.value[1];
  } else {
    queryParams.value.calculateTimeStart = "";
    queryParams.value.calculateTimeEnd = "";
  }
  emissionIndicatorLedgerlistLedgel(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}
const removechukuList = () => {
  localStorage.removeItem("chukuList");
};
/** 取消按钮 */

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "",
    isAsc: "",
    name: "",
    level: "",
    cycle: "",
    resultStatus: "",
    calculateTimeStart: "",
    calculateTimeEnd: "",
    orderBy: ""
  };
  if (localStorage.getItem("facList")) {
    let faclist = JSON.parse(localStorage.getItem("facList"));
    if (faclist.length == 1) {
      facDisabled.value = true;
      queryParams.value.level = faclist[0].name;
      getList();
    } else if (faclist.length == 2) {
      facDisabled.value = false;
      queryParams.value.level = null;
      getList();
    }
  }
  dateRange.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  equipdata.value = {
    name: "",
    serialNumber: "",
    category: "",
    relatedEnergy: "",
    emissionFactorId: "",
    emissionFactorName: "",
    unit: "",
    factorSource: "",
    activityLevelUnit: "",
    unitConversionRatio: null,
    emissionCategory: "",
    standardValueList: [],
    createByName: "",
    updateByName: ""
  };
}
const handlehistory = id => {
  queryParams2.value.id = id;
  getRukuList();
  innerVisible.value = true;
};
const handlehalarm = row => {
  alarmList.value = [];
  alarmVisible.value = true;
  getalarmList(row);
  indicatorLedgeId.value = row.id;
};
const handleEditor = async val => {
  buttonTitle.value = "编辑";
  addVisible.value = true;
  const data = await facilitydetail({ id: val });
  //console.log(data);

  equipdata.value = data;
};
/** 多选框选中数据 */
function handleSelectionChange2(selection) {
  console.log(selection);
  selectRukuList.value = selection;
}

// const addRukudetails = () => {
//   equipdata.value.details = [...equipdata.value.details, ...selectRukuList.value];
//   let seenIds = new Set();
//   let uniqueArr = [];
//   equipdata.value.details.forEach(obj => {
//     if (!seenIds.has(obj.inboundNumber)) {
//       uniqueArr.push(obj);
//       seenIds.add(obj.inboundNumber);
//     }
//   });
//   equipdata.value.details = [];
//   if (setChukuList(uniqueArr) == true) {
//     progressVisible.value = false;
//     equipdata.value.details = uniqueArr;
//   }
// };

let setChukuList = uniqueArr => {
  if (uniqueArr.length === 0) {
    PxMessage({
      message: "请选择要出库的数据",
      type: "error"
    });
    return false;
  }
  const firstname = uniqueArr[0].wasteName;
  for (let i = 1; i < uniqueArr.length; i++) {
    if (uniqueArr[i].wasteName != firstname) {
      PxMessage({
        message: "请选择相同的废弃物",
        type: "error"
      });
      return false;
    }
  }
  return true;
};

const handleDeleteRuku = row => {
  // console.log(row);
  equipdata.value.details = equipdata.value.details.filter(item => item != row);
};
const saveYinziku = () => {
  equipdata.value.emissionFactorId = selectrow.value.id;
  equipdata.value.emissionFactorName = selectrow.value.name;
  equipdata.value.value = selectrow.value.value;
  equipdata.value.unit = selectrow.value.unit;
  equipdata.value.factorSource = selectrow.value.factorSource;
  equipdata.value.releaseYear = selectrow.value.releaseYear;
  innerVisible.value = false;
  //selectrow
};
/** 提交按钮 */

const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      console.log(equipdata);
      const params = {
        name: equipdata.value.name,
        serialNumber: equipdata.value.serialNumber,
        category: equipdata.value.category,
        relatedEnergy: equipdata.value.relatedEnergy,
        emissionFactorId: equipdata.value.emissionFactorId,
        emissionFactorName: equipdata.value.emissionFactorName,
        unit: equipdata.value.unit,
        factorSource: equipdata.value.factorSource,
        activityLevelUnit: equipdata.value.activityLevelUnit,
        unitConversionRatio: equipdata.value.unitConversionRatio,
        emissionCategory: equipdata.value.emissionCategory,
        standardValueList: equipdata.value.standardValueList,
        createByName: JSON.parse(localStorage.getItem("userInfo")).username,
        updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
        releaseYear: equipdata.value.releaseYear,
        value: equipdata.value.value
      };
      if (buttonTitle.value == "新增") {
        facilitysave(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        getList();
      } else {
        const params2 = {
          id: equipdata.value.id,
          name: equipdata.value.name,
          serialNumber: equipdata.value.serialNumber,
          category: equipdata.value.category,
          relatedEnergy: equipdata.value.relatedEnergy,
          emissionFactorId: equipdata.value.emissionFactorId,
          emissionFactorName: equipdata.value.emissionFactorName,
          unit: equipdata.value.unit,
          factorSource: equipdata.value.factorSource,
          activityLevelUnit: equipdata.value.activityLevelUnit,
          unitConversionRatio: equipdata.value.unitConversionRatio,
          emissionCategory: equipdata.value.emissionCategory,
          standardValueList: equipdata.value.standardValueList,
          updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
          releaseYear: equipdata.value.releaseYear,
          value: equipdata.value.value
        };
        facilityedit(params2).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        getList();
      }
    }
  });
};
const handleCom = id => {
  PxMessageBox.confirm("确定重新计算该指标结果吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      // const data = await facilitydelete({ id: id });
      emissionIndicatorLedgercalculate({ id: id }).then(res => {
        PxMessage({
          message: "重新计算成功",
          type: "success"
        });
        getList();
      });
    })
    .catch(() => {});
};
/** 删除按钮操作 */
function handleDelete(row) {
  PxMessageBox.confirm("是否删除该条数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      // const data = await facilitydelete({ id: row.id });
      emissionIndicatorLedgerdeleteLedge({ id: row.id }).then(res => {
        PxMessage({
          message: "删除成功",
          type: "success"
        });
        getList();
      });
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  const dictIds = [];
  dictIds.push(...ids.value);
  const params = { ids: dictIds };
  proxy.download("post", "/operation/api/v1/water/hazardWasteOut/export", params, "危险废弃物出库.xlsx");
}

function translateTime(cycle, time) {
  let res = time.substring(0, 10);
  switch (cycle) {
    case "年":
      const year = time.substring(0, 4);
      break;
    case "月":
      res = time.substring(0, 7);
      break;
    case "日":
      res = time.substring(0, 10);
      break;
    default:
      break;
  }
  return res;
}
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.status-value {
  color: #10b981;
}

.status-icon {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 8px;
  background: #10b981;
  border-radius: 50%;
}

.status-value2 {
  color: red;
}

.status-icon2 {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 8px;
  background: red;
  border-radius: 50%;
}
</style>
